<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { chain, each } from 'lodash'
import * as echarts from 'echarts'
import useApi from '@/core/apiStore'
import dayjs from 'dayjs'

interface ClusterData {
  name: string
  total: number
  error: number
}

const apiStore = useApi()
const loading = ref(false)

// 模拟获取集群数据
const getClusters = async (): Promise<ClusterData[]> => {
  loading.value = true
  try {
    const {
      data: { clusters = [] },
    } = await apiStore.getClusters()

    // 所有的business
    const businesses = await apiStore.getBusinessItems()
    const businessNames = chain(businesses)
      .map(item => item.name)
      .value()

    // 将结束时间设置为当前时间，将开始时间设置为当前时间向前5小时
    const endTime = dayjs().format('YYYY-MM-DD HH:mm:ss')
    const startTime = dayjs().subtract(5, 'hour').format('YYYY-MM-DD HH:mm:ss')

    // 重构为更清晰的异步处理流程
    const searchTags = await Promise.all(
      businessNames.map(async name => {
        const res = await apiStore.buildTopoAnalysis({
          startTime,
          endTime,
          business_name: name,
          useWarningCondition: true,
        })
        return res.data.search_tag
      })
    )

    const clusterLogs = await Promise.all(
      searchTags.map(async searchTag => {
        const res = await apiStore.searchClusterLogInfo({
          search_tag: searchTag,
        })
        return res.data
      })
    )

    const clusterIpCount = chain(clusterLogs)
      .map(item => item.logs)
      .flatten()
      .reduce((acc, { ip, total, warning }) => {
        if (!acc[ip]) {
          acc[ip] = { total: 0, warning: 0 }
        }
        acc[ip].total += total
        acc[ip].warning += warning
        return acc
      }, {})
      .value()

    const chartData = clusters.map(({ name, ips }) => {
      const result = { name, total: 0, error: 0 }

      each(ips, ip => {
        const clusterIpInfo = clusterIpCount[ip]
        if (clusterIpInfo) {
          result.total += clusterIpInfo.total
          result.error += clusterIpInfo.warning
        }
      })
      return result
    })

    console.log('chartData', chartData) // 测试后可以直接使用chartData
    return chartData
    /*
    return clusters.map(({ name }) => ({
      name,
      total: Math.floor(Math.random() * 1000) + 100,
      error: Math.floor(Math.random() * 100),
    }))
    */
  } finally {
    loading.value = false
  }
}

const chartRef = ref<HTMLElement | null>(null)

onMounted(async () => {
  if (!chartRef.value) return

  const chart = echarts.init(chartRef.value)
  const clustersData = await getClusters()

  const option = {
    title: {
      text: '日志集群统计',
      left: 'center',
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow',
      },
    },
    legend: {
      data: ['总日志量', '异常日志量'],
      top: 30,
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true,
    },
    xAxis: {
      type: 'value',
    },
    yAxis: {
      type: 'category',
      data: clustersData.map(item => item.name),
    },
    series: [
      {
        name: '总日志量',
        type: 'bar',
        stack: 'total',
        label: {
          show: true,
          position: 'inside',
        },
        emphasis: {
          focus: 'series',
        },
        data: clustersData.map(item => item.total),
        itemStyle: {
          color: '#5470c6',
        },
      },
      {
        name: '异常日志量',
        type: 'bar',
        stack: 'total',
        label: {
          show: true,
          position: 'inside',
        },
        emphasis: {
          focus: 'series',
        },
        data: clustersData.map(item => item.error),
        itemStyle: {
          color: '#ee6666',
        },
      },
    ],
  }

  chart.setOption(option)

  // 响应式调整
  const resizeHandler = () => chart.resize()
  window.addEventListener('resize', resizeHandler)

  // 组件卸载时清理
  onUnmounted(() => {
    window.removeEventListener('resize', resizeHandler)
    chart.dispose()
  })
})
</script>

<template>
  <div
    ref="chartRef"
    v-loading="loading"
    style="width: 100%; height: 400px"
  ></div>
</template>
